package com.classbook.violet.baigiang6.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.classbook.violet.baigiang6.activity.MainActivity;
import com.classbook.violet.baigiang6.database.DatabaseHelper;
import com.classbook.violet.baigiang6.fragment.MFragmentAdapter;
import com.classbook.violet.baigiang6.model.ConnectionDetector;
import com.classbook.violet.baigiang6.model.ExternalStorage;
import com.classbook.violet.baigiang6.subject.LessonNode;
import com.classbook.violet.baigiang7.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListLessonAdapter extends BaseAdapter{
	
	private boolean is_teacher = false;
	
	private String URL = "http://classbook.vn/cbs/violet/download";
	private String PATH_I = Environment.getExternalStorageDirectory().getPath() + "/EDC/Violet/";
	private String PATH_E = Environment.getExternalStorageDirectory().getPath() + "/external_sdcard/";
	private Context context;
	private List<LessonNode> listSubject;
	private List<LessonNode> listAllSub;
	private static LayoutInflater inflater=null;
	
//	private List<Boolean> listCheck = new ArrayList<Boolean>();
//	private List<Boolean> listCheckFile = new ArrayList<Boolean>();
	private ConnectionDetector mConnect;
	Map<String, File> externalLocations;
	String type_adapter;
	
	public Boolean isDownloading = false;
	
	Bitmap bm_default;
	private File file_nguon, file_dich;
	private ProgressDialog pDialog;
	
//	private GlobalVar global;
	DatabaseHelper db;
	
	public ListLessonAdapter (Context context, List<LessonNode> listSubject, String type_adapter){
		File direc_file = new File(PATH_E);
//		Log.d("EXTERNAL SDCARD", "" + direc_file.listFiles().length);
		this.context = context;
		this.type_adapter = type_adapter;
		this.db = new DatabaseHelper(context);
		this.listAllSub = listSubject;
		this.listSubject = new ArrayList<LessonNode>();
		bm_default = BitmapFactory.decodeResource(context.getResources(), R.drawable.video); 
		if (this.listAllSub.size() > 0){
			this.listSubject.add(this.listAllSub.get(0));
		}
//		for (int i = 0; i < listSubject.size(); i++){
//			this.listCheck.add(false);
//			this.listCheckFile.add(false);
//		}
		inflater = ((Activity) context).getLayoutInflater();
		mConnect = new ConnectionDetector(context);
		externalLocations = ExternalStorage.getAllStorageLocations();
		if (Build.DISPLAY.contains("CBT")){
			is_teacher = true;
		}else{
			is_teacher = false;
		}
		
//		is_teacher = true;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listSubject.size();
	}

	@Override
	public LessonNode getItem(int arg0) {
		// TODO Auto-generated method stub
		return listSubject.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	public class bookHolder{
		TextView title;
		ImageView thumb;
		LinearLayout ll_content;
		
		LinearLayout ll_video;
		LinearLayout ll_ppt;
		LinearLayout ll_like;
		LinearLayout ll_delete;
		LinearLayout ll_save;
		
		ImageView iv_video;
		ImageView iv_ppt;
		ImageView iv_like;
		ImageView iv_delete;
		
		TextView tv_video;
		TextView tv_ppt;
		TextView tv_like;
		TextView tv_delete;
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(final int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		 View vi = arg1;
		 //Log.d("VIEW", "Posiontion: " + arg0);
	      if(arg1 == null){
	    	  vi = inflater.inflate(R.layout.row_book, null);
	    	  
	    	  bookHolder holder = new bookHolder();
	    	  
	    	  holder.title = (TextView) vi.findViewById(R.id.tv_book_title);
	    	  holder.thumb = (ImageView) vi.findViewById(R.id.iv_cover);
	    	  holder.ll_content = (LinearLayout) vi.findViewById(R.id.ll_content);

	    	  holder.ll_video = (LinearLayout) vi.findViewById(R.id.ll_video);
	    	  holder.ll_ppt = (LinearLayout) vi.findViewById(R.id.ll_ppt);
	    	  holder.ll_like = (LinearLayout) vi.findViewById(R.id.ll_like);
	    	  holder.ll_delete = (LinearLayout) vi.findViewById(R.id.ll_delete);
	    	  holder.ll_save = (LinearLayout) vi.findViewById(R.id.ll_save);
	    	  
	    	  holder.iv_video = (ImageView) vi.findViewById(R.id.iv_video);
	    	  holder.iv_ppt = (ImageView) vi.findViewById(R.id.iv_ppt);
	    	  holder.iv_like = (ImageView) vi.findViewById(R.id.iv_like);
	    	  holder.iv_delete = (ImageView) vi.findViewById(R.id.iv_delete);
	    	  
	    	  holder.tv_video = (TextView) vi.findViewById(R.id.tv_video);
	    	  holder.tv_ppt = (TextView) vi.findViewById(R.id.tv_ppt);
	    	  holder.tv_like = (TextView) vi.findViewById(R.id.tv_like);
	    	  holder.tv_delete = (TextView) vi.findViewById(R.id.tv_delete);
	    	  
	    	  vi.setTag(holder);
	      }
	      
	      final bookHolder holder = (bookHolder) vi.getTag();
	      holder.ll_like.setEnabled(false);
	      
	      holder.title.setText(listSubject.get(arg0).label);
	      File file_cover = new File(PATH_I + listSubject.get(arg0).path + ".jpg");
	      if (file_cover.exists() && listSubject.get(arg0).cover == null && listSubject.get(arg0).isLoadCover){
	    	  Bitmap bm = BitmapFactory.decodeFile(PATH_I + listSubject.get(arg0).path + ".jpg");
	    	  listSubject.get(arg0).cover = Bitmap.createScaledBitmap(bm, 160, 120, true);
	    	  holder.thumb.setImageBitmap(listSubject.get(arg0).cover);
	    	  listSubject.get(arg0).isLoadCover = false;
	    	  bm.recycle();
	      }else if (file_cover.exists() && listSubject.get(arg0).cover != null){
	    	  holder.thumb.setImageBitmap(listSubject.get(arg0).cover);
	    	  listSubject.get(arg0).isLoadCover = false;
	      }else if (!file_cover.exists()){
	    	  holder.thumb.setImageResource(R.drawable.video);
	    	  if (listSubject.get(arg0).isLoadCover){
		    	  HashMap<String, Object> hm = new HashMap<String, Object>();
		    	  hm.put("cover_path", listSubject.get(arg0).path);
		    	  hm.put("position", arg0);
		    	  listSubject.get(arg0).isLoadCover = false;
		    	  listSubject.get(arg0).cover = bm_default;
		    	  holder.thumb.setImageBitmap(listSubject.get(arg0).cover);
		    	  new LoadCoverImage().execute(hm);
	    	  }else {
	    		  holder.thumb.setImageBitmap(listSubject.get(arg0).cover);
	    	  }
	      }
	      
	       final File file_internal_wmv = new File(PATH_I + listSubject.get(arg0).path + ".wmv");
	       final File file_internal_ppt = new File(PATH_I + listSubject.get(arg0).path + ".ppt");

	       holder.ll_delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Log.v("CLICK DELETE", "CLICK");
					if (file_internal_wmv.exists() && !file_internal_ppt.exists()){
						AlertDialog.Builder al_remove = new AlertDialog.Builder(context);
						al_remove.setTitle("Xóa Video?");
						al_remove.setMessage(listSubject.get(arg0).label + " ?");
						al_remove.setIcon(R.drawable.playvideo);
						al_remove.setPositiveButton("Có",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										if (file_internal_wmv.delete()){
											Toast.makeText(context, "Xóa thành công !", Toast.LENGTH_LONG).show();
											  holder.ll_delete.setVisibility(View.GONE);
											  holder.ll_like.setVisibility(View.GONE);
									    	  holder.iv_video.setImageResource(R.drawable.taivideo);
									    	  holder.ll_delete.setClickable(false);
									    	  db.deleteRecent(listSubject.get(arg0));
									    	  db.removeLessonCategory("like", listSubject.get(arg0));
									    	  if (type_adapter.contains("menu")){
									    		  listSubject.remove(arg0);
									    		  ListLessonAdapter.this.notifyDataSetChanged();
									    	  }
										}else {
											Toast.makeText(context, "Xóa thất bại !", Toast.LENGTH_LONG).show();
										}
									}
								});
						al_remove.setNegativeButton("Không",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										dialog.cancel();
									}
								});
						al_remove.show();
					}else if (!file_internal_wmv.exists() && file_internal_ppt.exists()){
						AlertDialog.Builder al_remove = new AlertDialog.Builder(context);
						al_remove.setTitle("Xóa PowerPoint?");
						al_remove.setMessage(listSubject.get(arg0).label + " ?");
						al_remove.setIcon(R.drawable.ppt1);
						al_remove.setPositiveButton("Có",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										if (file_internal_ppt.delete()){
											Toast.makeText(context, "Xóa thành công !", Toast.LENGTH_LONG).show();
											  holder.ll_delete.setVisibility(View.GONE);
											  holder.ll_like.setVisibility(View.GONE);
									    	  holder.iv_ppt.setImageResource(R.drawable.ppt2);
									    	  holder.ll_delete.setClickable(false);
									    	  holder.ll_save.setVisibility(View.GONE);
									    	  db.deleteRecent(listSubject.get(arg0));
									    	  db.removeLessonCategory("like", listSubject.get(arg0));
									    	  if (type_adapter.contains("menu")){
									    		  listSubject.remove(arg0);
									    		  ListLessonAdapter.this.notifyDataSetChanged();
									    	  }
										}else {
											Toast.makeText(context, "Xóa thất bại !", Toast.LENGTH_LONG).show();
										}
									}
								});
						al_remove.setNegativeButton("Không",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										dialog.cancel();
									}
								});
						al_remove.show();
					}else if (file_internal_wmv.exists() && file_internal_ppt.exists()){
						final Dialog remove_dialog = new Dialog(context);
						remove_dialog.setContentView(R.layout.dialog_list);
						remove_dialog.setTitle("Lựa chọn một phương án xóa");
						ListView lv = (ListView) remove_dialog.findViewById(R.id.lv_dialog);
						String[] action = {"Xóa Video", "Xóa PowerPoint", "Xóa cả Video và PowerPoint"};
						ArrayAdapter< String> adapter = new ArrayAdapter<String>(context, 
								android.R.layout.simple_list_item_1, action);
						lv.setAdapter(adapter);
						lv.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg, View arg1,
									int arg2, long arg3) {
								// TODO Auto-generated method stub
								if (arg2 == 0){
									if(file_internal_wmv.delete()){
										Toast.makeText(context, "Xóa thành công !", Toast.LENGTH_LONG).show();
										holder.iv_video.setImageResource(R.drawable.taivideo);
										remove_dialog.dismiss();
									}else{
										Toast.makeText(context, "Xóa thất bại !", Toast.LENGTH_LONG).show();
									}
								}else if (arg2 == 1){
									if (file_internal_ppt.delete()){
										holder.iv_ppt.setImageResource(R.drawable.ppt2);
										holder.ll_save.setVisibility(View.GONE);
										Toast.makeText(context, "Xóa thành công !", Toast.LENGTH_LONG).show();
										remove_dialog.dismiss();
									}else {
										Toast.makeText(context, "Xóa thất bại !", Toast.LENGTH_LONG).show();
									}
								}else if (arg2 == 2){
									Toast.makeText(context, "Xóa thành công !", Toast.LENGTH_LONG).show();
									file_internal_wmv.delete();
									file_internal_ppt.delete();
									holder.ll_delete.setVisibility(View.GONE);
									  holder.ll_like.setVisibility(View.GONE);
							    	  holder.iv_ppt.setImageResource(R.drawable.ppt2);
							    	  holder.ll_save.setVisibility(View.GONE);
							    	  holder.iv_video.setImageResource(R.drawable.taivideo);
							    	  holder.ll_delete.setClickable(false);
							    	  db.deleteRecent(listSubject.get(arg0));
							    	  db.removeLessonCategory("like", listSubject.get(arg0));
							    	  if (type_adapter.contains("menu")){
							    		  listSubject.remove(arg0);
							    		  ListLessonAdapter.this.notifyDataSetChanged();
							    	  }
									
									remove_dialog.dismiss();
								}
							}
						});
						remove_dialog.show();
					}
				}
	    	  }); 
	      if (!file_internal_wmv.exists() && !file_internal_ppt.exists()){
	    	  holder.ll_like.setVisibility(View.GONE);
	    	  holder.ll_delete.setVisibility(View.GONE);
	      }else{
	    	  holder.ll_like.setVisibility(View.VISIBLE);
	    	  holder.ll_delete.setVisibility(View.VISIBLE);
	    	  if (listSubject.get(arg0).isLike){
	    		  holder.iv_like.setImageResource(R.drawable.uathich);
	    		  holder.tv_like.setTextColor(Color.parseColor("#F2D013"));
	    	  }else{
	    		  holder.iv_like.setImageResource(R.drawable.pin);
	    		  holder.tv_like.setTextColor(Color.parseColor("#3294D8"));
	    	  }
	    	  
	      }
	       
	      if (!file_internal_wmv.exists()){
	    	  holder.iv_video.setImageResource(R.drawable.taivideo);
	    	  
	      }else {
	    	  holder.iv_video.setImageResource(R.drawable.playvideo);
	      }
	    	  //if file not ready
	      
	      
	        /* Show the progress dialog. */
	      holder.ll_video.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!file_internal_wmv.exists()){
					DownloadFile(arg0, ".wmv", holder);
				}else{
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);
					i.setDataAndType(Uri.fromFile(file_internal_wmv), "video/wmv");
					db.addNewRecent(listSubject.get(arg0));
					context.startActivity(i);
				}
			}
	      });
	      holder.iv_like.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.d("TYPE-UNLIKE", type_adapter);
					if (file_internal_wmv.exists() || file_internal_ppt.exists()){
					if (listSubject.get(arg0).isLike){
						db.removeLessonCategory("like", listSubject.get(arg0));
						holder.iv_like.setImageResource(R.drawable.pin);
						holder.tv_like.setTextColor(Color.parseColor("#3294D8"));
						listSubject.get(arg0).isLike = false;
						if (type_adapter.contains("like")){
							listSubject.remove(arg0);
					    	ListLessonAdapter.this.notifyDataSetChanged();
						}
					}else {
						db.addLessonCategory("like", listSubject.get(arg0));
						holder.iv_like.setImageResource(R.drawable.uathich);
						holder.tv_like.setTextColor(Color.parseColor("#F2D013"));
						listSubject.get(arg0).isLike = true;
						
					}
					}
				}
	    	  });
	      holder.ll_content.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (file_internal_wmv.exists()){
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);
					i.setDataAndType(Uri.fromFile(file_internal_wmv), "video/wmv");
					db.addNewRecent(listSubject.get(arg0));
					context.startActivity(i);
				}
			}
		});
	      if (!file_internal_ppt.exists()){
	    	  holder.ll_save.setVisibility(View.GONE);
	    	  holder.iv_ppt.setImageResource(R.drawable.ppt2);
	      }else{
	    	  holder.ll_save.setVisibility(View.VISIBLE);
	    	  holder.iv_ppt.setImageResource(R.drawable.ppt1);
	      }
	      if (is_teacher){
	    	  holder.ll_ppt.setVisibility(View.VISIBLE);
	      
	      holder.ll_ppt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Log.d("FILE_LINK", listSubject.get(arg0).file_link);
				if (!file_internal_ppt.exists()){
					DownloadFile(arg0, ".ppt", holder);
				}else {
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);
					i.setDataAndType(Uri.fromFile(new File(PATH_I + listSubject.get(arg0).path + ".ppt"))
							, "application/vnd.ms-powerpoint");
//					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


					try {
						db.addNewRecent(listSubject.get(arg0));
						context.startActivity(i);
					} 
					catch (ActivityNotFoundException e) {
					    Toast.makeText(context, 
					        "No Application Available to View ppt", 
					        Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	      }else {
	    	  holder.ll_ppt.setVisibility(View.INVISIBLE);
	      }
	      
	      holder.ll_save.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (file_internal_ppt.exists()){
						if (checkSDcard()){
							final Dialog dialog_save = new Dialog(context);
							dialog_save.setTitle("Lưu file PowerPoint vào thẻ nhớ");
							dialog_save.setContentView(R.layout.dialog_edit);
							final EditText et_edit = (EditText)
									dialog_save.findViewById(R.id.et_save_edit);
							Button b_save = (Button)
									dialog_save.findViewById(R.id.b_save);
							et_edit.setText(file_internal_ppt.getName());
							b_save.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog_save.dismiss();
									File save_file = new File(PATH_E + et_edit.getText());
									try {
										copyFile(file_internal_ppt, save_file);
										Toast.makeText(context, save_file.getPath(), Toast.LENGTH_LONG);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
										Toast.makeText(context, e.toString(), Toast.LENGTH_LONG);
									}
									
									
									
								}
							});
							dialog_save.show();
						}else{
							AlertDialog.Builder al_connect = new AlertDialog.Builder(context);
							al_connect.setTitle("Không tìm thấy thẻ nhớ!");
							al_connect.setMessage("Cắm thẻ nhớ vào máy để sao chép file");
							
							al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									dialog.cancel();
								}
							});
							al_connect.show();
						}
					}
				}
			});
	      
	      
	     getNextView(arg0); 
	     
		 return vi;
	}
	
	protected boolean checkSDcard() {
		// TODO Auto-generated method stub
		boolean check = false;
		File sdCardFile = new File(PATH_E);
		if (sdCardFile.listFiles().length == 0){
			check = false;
		}else {
			check = true;
		}
		return check;
	}

	public String convertDungLuong(int progress){
		int m = 1024 * 1024;
		int k = 1024;
		String convert = "";
		if (progress < 1024){
			convert = "" + (int)progress + "B";
		}else if (progress >= k && progress < m){
			convert = "" + (int)(progress / k) + "." + ((int)(progress * 10 / k) - (int)(progress / k) * 10) + "KB";		
		}else if (progress >= m ){
			convert = "" + (int)(progress / m) + "." + ((int)(progress * 10 / m) - (int)(progress / m) * 10) + "MB";
		}
		return convert;
	}
	
	public Boolean deleteFile (String filePath){
		File delete_document = new File(filePath);
		return delete_document.delete();
	}
	
	public  void copyFile(File src, File dst) throws IOException
	{
		
	    file_nguon = src;
	    file_dich = dst;
	    new AsyntaskCopy().execute();
	}
	
	public class LoadCoverImage extends AsyncTask<HashMap<String, Object>, Void, Bitmap>{

		private Integer position_cover;

		@Override
		protected Bitmap doInBackground(HashMap<String, Object>... hm) {
			// TODO Auto-generated method stub
			String coverPath = hm[0].get("cover_path").toString();
			position_cover = (Integer) hm[0].get("position");
			Log.i(type_adapter, "" + position_cover);
			InputStream iStream=null;
			try{
				String filename = (coverPath + ".jpg").replaceAll(" ", "%20");
				URL mUrl = new URL(URL + "?filename=" + filename);
				HttpURLConnection urlConnection = (HttpURLConnection) mUrl.openConnection();

				urlConnection.setRequestMethod("POST");
				urlConnection.addRequestProperty("authorization", "Violet@2013");
				urlConnection.connect();

	            // Reading data from url 
	            iStream = urlConnection.getInputStream();
	            
	            // Getting Caching directory 
	            //File cacheDirectory = getActivity().getCacheDir();
	            
	            // Temporary file to store the downloaded image 
	            //File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+ position_cover +".png");
	            File SDCardRoot = new File(PATH_I + listSubject.get(position_cover).file_link);
				if (!SDCardRoot.exists()){
					SDCardRoot.mkdirs();
				}
	            File imageFile = new File(SDCardRoot, coverPath.split("/")[coverPath.split("/").length - 1] + ".jpg");
	            if (!imageFile.exists()) {
				    try {
				    	
				    	imageFile.createNewFile();
				    } catch (IOException e) {
				        e.printStackTrace();
				    }
				}
	               	
	            // The FileOutputStream to the temporary file
	            FileOutputStream fOutStream = new FileOutputStream(imageFile);
	            
	            BitmapFactory.Options options = new BitmapFactory.Options();
	    		options.inPreferredConfig = Config.RGB_565;
	    		options.inSampleSize = 4;
	    		
	            Bitmap b = BitmapFactory.decodeStream(iStream);	            
	            
	            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);	    
	            
	            // Flush the FileOutputStream
	            fOutStream.flush();
	            
	            //Close the FileOutputStream
	            fOutStream.close();
	            
	            Log.d("LoadImage", "Bitmap"+ position_cover +": "  + b.toString());
	            
	            return b;
	            
			}catch (Exception e){
				listSubject.get(position_cover).isLoadCover = false;
				Log.e("LoadImage", e.toString());
				return bm_default;
			}
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			listSubject.get(position_cover).cover = Bitmap.createScaledBitmap(result, 160, 120, true);
//			result.recycle();
			listSubject.get(position_cover).isLoadCover = false;
			notifyDataSetChanged();
		}
		
	}
	
	public void getNextView(int pos){
		if (pos == listSubject.size() - 1 && pos < listAllSub.size() - 1){
			
			listSubject.add(listAllSub.get(pos + 1));
			notifyDataSetChanged();
		}
	}
	
	public void DownloadFile(int position, String type_file, bookHolder b_holder){
		final bookHolder holder = b_holder;
		final String type = type_file;
		final int arg0 = position;
			if (mConnect.isConnectingToInternet()){
			AlertDialog.Builder al_down = new AlertDialog.Builder(context);
			al_down.setTitle("Tải về");
			if (type.equals(".wmv")){
				al_down.setIcon(R.drawable.playvideo);
			}else {
				al_down.setIcon(R.drawable.ppt1);
			}
			al_down.setMessage(listSubject.get(arg0).label + "?");
			al_down.setPositiveButton("Có", new DialogInterface.OnClickListener() {
				
				@SuppressWarnings("deprecation")
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
//					listCheck.set(arg0, true);
					listSubject.get(arg0).isDownload = true;
					isDownloading = true;
					final ProgressDialog myProgress = new ProgressDialog(context);
			    	myProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			    	myProgress.setMessage(listSubject.get(arg0).label);
			    	myProgress.setTitle("Đang tải về ");
			    	myProgress.setIcon(R.drawable.down);
			    	myProgress.setCancelable(false);
			    	myProgress.setButton("Hủy tải về", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        	isDownloading = false;
                        }
                    });
			    	myProgress.show();
					new Thread( new Runnable() {
						
						@Override
						public void run() {
							
							try{
//								time_out++;
								//Connecttion down video
								String filename = (listSubject.get(arg0).path + type).replaceAll(" ", "%20");
								URL url = new URL(URL + "?filename=" + filename);
								Log.i("URL", url.toString());
								final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

								urlConnection.setRequestMethod("POST");
								urlConnection.addRequestProperty("authorization", "Violet@2013");
								urlConnection.connect();
								File SDCardRoot = new File(PATH_I + listSubject.get(arg0).file_link);
								if (!SDCardRoot.exists()){
									SDCardRoot.mkdirs();
								}

								final File file = new File(SDCardRoot,listSubject.get(arg0).url + type);
								if (!file.exists()) {
								    try {
								    	
								        file.createNewFile();
								    } catch (IOException e) {
								        e.printStackTrace();
								    }
								}

								FileOutputStream fileOutput = new FileOutputStream(file);

								InputStream inputStream = urlConnection.getInputStream();
								
								//Connection Down thumb
								
//								String thumname = (listSubject.get(arg0).path + ".jpg").replaceAll(" ", "%20");
//								URL url_thumb = new URL(URL + "?filename=" + thumname);
//								final HttpURLConnection urlConnection_thumb = (HttpURLConnection) url_thumb.openConnection();
//
//								urlConnection_thumb.setRequestMethod("POST");
//								urlConnection_thumb.addRequestProperty("authorization", "Violet@2013");
//								urlConnection_thumb.connect();
//
//								final File file_thumb = new File(SDCardRoot,listSubject.get(arg0).url + ".jpg");
//								if (!file.exists()) {
//								    try {
//								    	
//								        file.createNewFile();
//								    } catch (IOException e) {
//								        e.printStackTrace();
//								    }
//								}
//
//								FileOutputStream fileOutputThumb = new FileOutputStream(file_thumb);
//
//								InputStream inputStreamThumb = urlConnection_thumb.getInputStream();
								
								//
								int totalSize;
								int downloadedSize;
								int sizeVideo = urlConnection.getContentLength();
//								int sizeThumb = urlConnection_thumb.getContentLength();
//								totalSize = sizeVideo + sizeThumb;
								totalSize = sizeVideo;
								//myProgress.setMessage("Tổng dung lượng: " + convertDungLuong(totalSize));
								myProgress.setMax(100);
//								Log.i("" + sizeVideo, "" + sizeThumb);
								Log.i("TOTAL SIZE DOWNLOAD", "" + totalSize);
								listSubject.get(arg0).totalSize = totalSize;
								listSubject.get(arg0).isDownSart = true;
								downloadedSize = 0;

								byte[] buffer = new byte[1024*1024];
//								byte[] buffer_thumb = new byte[1024*1024];
								int bufferLength = 0;
//								int bufferLenght_thumb = 0;


								while ( (bufferLength = (inputStream.read(buffer))) > 0) {
//									while ((bufferLenght_thumb = inputStreamThumb.read(buffer_thumb)) > 0){
//										fileOutputThumb.write(buffer_thumb, 0, bufferLenght_thumb);
//										downloadedSize += bufferLenght_thumb;
//										time_out = 0;
//										listSubject.get(arg0).downSize = downloadedSize;
//										final int progress=(int) (downloadedSize / (totalSize/100));
//										//Log.i("SIZE", "" + downloadedSize + " / " + totalSize + "----" + progress + "%" );
//										myProgress.setProgress(progress);
//										global.setSize(listSubject.get(arg0));
//									}
									
									fileOutput.write(buffer, 0, bufferLength);
									
//									Log.i("" + bufferLength, "" + bufferLenght_thumb) ;
									
//									downloadedSize += ((bufferLength) + bufferLenght_thumb) ;
									downloadedSize += ((bufferLength));
									listSubject.get(arg0).downSize = downloadedSize; 
									
									final int progress=(int) (downloadedSize / (totalSize/100));
									
									myProgress.setProgress(progress);
//									global.setSize(listSubject.get(arg0));
									mConnect = new ConnectionDetector(context);
									if (!mConnect.isConnectingToInternet()){
										urlConnection.disconnect();
										Thread.interrupted();
//										listCheck.set(arg0, false);
										listSubject.get(arg0).isDownload = false;
//										listCheckFile.set(arg0, false);
										
//								    	holder.iv_like.setVisibility(View.INVISIBLE);
//								    	holder.iv_delete_down.setImageResource(R.drawable.download);
//								    	holder.iv_delete_down.setClickable(false);
										file.delete();
										//file_thumb.delete();
										myProgress.cancel();
									}
									
									if (!isDownloading){
										urlConnection.disconnect();
										Thread.interrupted();
//										listCheck.set(arg0, false);
										listSubject.get(arg0).isDownload = false;
//										listCheckFile.set(arg0, false);
										
//								    	holder.iv_like.setVisibility(View.INVISIBLE);
//								    	holder.iv_delete_down.setImageResource(R.drawable.download);
//								    	holder.iv_delete_down.setClickable(false);
										file.delete();
										//file_thumb.delete();
									}
									
									Thread.sleep(1000);

								}
								myProgress.dismiss();
								listSubject.get(arg0).isDownComplete = true;
								if (type.equals(".wmv")){
								holder.ll_content.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										holder.ll_delete.setVisibility(View.VISIBLE);
								    	holder.ll_like.setVisibility(View.VISIBLE);
								    	holder.ll_delete.setClickable(true);
								    	holder.iv_video.setImageResource(R.drawable.playvideo);
								  
									}
								});
								}else if (type.equals(".ppt")){
									holder.iv_ppt.post(new Runnable() {
										public void run() {
											holder.ll_delete.setVisibility(View.VISIBLE);
									    	holder.ll_like.setVisibility(View.VISIBLE);
									    	holder.ll_delete.setClickable(true);
											holder.iv_ppt.setImageResource(R.drawable.ppt1);
											holder.ll_save.setVisibility(View.VISIBLE);
											holder.iv_ppt.setOnClickListener(new OnClickListener() {
												
												@Override
												public void onClick(View v) {
													// TODO Auto-generated method stub
													Intent i = new Intent();
													i.setAction(android.content.Intent.ACTION_VIEW);
	//												if (file_internal.exists()){
													i.setDataAndType(Uri.fromFile(new File(PATH_I + listSubject.get(arg0).path + type))
															, "application/vnd.ms-powerpoint");
//													intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


													try {
														db.addNewRecent(listSubject.get(arg0));
														context.startActivity(i);
													} 
													catch (ActivityNotFoundException e) {
													    Toast.makeText(context, 
													        "No Application Available to View ppt", 
													        Toast.LENGTH_SHORT).show();
													}
													
												}
											});
										}
									});
								}
//								listCheck.set(arg0, false);
//								listCheckFile.set(arg0, true);
								listSubject.get(arg0).isDownload = false;
								
								Thread.interrupted();

								fileOutput.close();
								
							}catch (final Exception e){
//								listCheck.set(arg0, false);
								listSubject.get(arg0).isDownload = false;
//								listCheckFile.set(arg0, false);
										new File(PATH_I + listSubject.get(arg0).path + type).delete();
										//new File(PATH_I + listSubject.get(arg0).path + ".jpg").delete();
										//Toast.makeText(context, "Khong tim thay file", Toast.LENGTH_LONG);
								myProgress.cancel();
								if (isDownloading){
								holder.ll_content.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										AlertDialog.Builder al_connect = new AlertDialog.Builder(context);
										String error = "";
										if (e.toString().contains("FileNotFound")){
											error = "Không tìm thấy file";
										}else {
											error = "Không có kết nối";
										}
										al_connect.setTitle(error);
										//al_connect.setMessage(e.toString());
										
										al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,int id) {
												dialog.cancel();
											}
										});
										al_connect.show(); 
									}
								});
								isDownloading = false;
								}
								
								Log.e("DOWNLOAD ERROR", e.toString());
							}
						}
					}).start();
				}
			});
			al_down.setNegativeButton("Không",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			});
			al_down.show();
			
			}
			else {
				AlertDialog.Builder al_connect = new AlertDialog.Builder(context);
				al_connect.setTitle("Không có kết nối");
				al_connect.setMessage("Bật wifi hoặc 3G để tải về");
				
				al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});
				al_connect.show();
			}
			
	}
	
	public class AsyntaskCopy extends AsyncTask<String, String, Boolean>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Đang sao chép vào thẻ nhớ");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			FileChannel inChannel;
			try {
				inChannel = new FileInputStream(file_nguon).getChannel();
				FileChannel outChannel = new FileOutputStream(file_dich).getChannel();
			    try
			    {
			        inChannel.transferTo(0, inChannel.size(), outChannel);
			    }
			    finally
			    {
			        if (inChannel != null)
			            inChannel.close();
			        if (outChannel != null)
			            outChannel.close();
			    }
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO: handle exception
			}
		    
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.cancel();
			AlertDialog.Builder al_connect = new AlertDialog.Builder(context);
			al_connect.setCancelable(false);
			al_connect.setTitle("Thành công!");
			al_connect.setMessage("File đã được chép vào thẻ nhớ");
			
			al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			});
			al_connect.show();
		}
		
	}

}
